package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceResponse;
import com.google.common.collect.Maps;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.*;
import com.jsh.erp.datasource.vo.DepotHeadVo4List;
import com.jsh.erp.ding.DingService;
import com.jsh.erp.service.depotHead.DepotHeadService;
import com.jsh.erp.service.depotItem.DepotItemService;
import com.jsh.erp.service.project.ProjectService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import com.jsh.erp.utils.ErpInfo;
import com.jsh.erp.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;

@RestController
@RequestMapping(value = "/ding")
@Api(tags = {"钉钉相关接口"})
public class DingController {
    private Logger logger = LoggerFactory.getLogger(DingController.class);

    @Resource
    private ProjectService projectService;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private UserBusinessService userBusinessService;

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private UserService userService;
    @Resource
    private DingService dingService;
    @Resource
    private DepotHeadService depotHeadService;
    @Resource
    private DepotItemService depotItemService;
    @Resource
    private ProjectDepotHeadMapper projectDepotHeadMapper;
    @Resource
    private ContractDepotMapper contractDepotMapper;
    @Resource
    private ContractMapper contractMapper;
    @Resource
    private DepotHeadDingMapper depotHeadDingMapper;
    @Resource
    private SupplierService supplierService;
    @Resource
    private DepotHeadMapper depotHeadMapper;

    @PostMapping(value = "/start-process-instance/purchase-apply")
    @ApiOperation(value = "发起采购申请流程")
    public String startProcessInstanceApply(@RequestBody JSONObject jsonObject,
                                            HttpServletRequest request)throws Exception {
        Long userId = userService.getUserId(request);
        String depotHeadId = jsonObject.getString("depotHeadId");
        DepotHead depotHead = depotHeadService.getDepotHead(Long.parseLong(depotHeadId));
        if ( !depotHead.getStatus().equals(BusinessConstants.BILLS_STATUS_UN_AUDIT) ){
            return returnJson(Maps.newHashMap(), "只有未审核的单据才能发起审批流程，请刷新页面确认该单据是否已经审核完成！", ErpInfo.ERROR.code);
        }

        Project project = getDeportProject(depotHead.getId());
//        Contract contract = getDeportContract(depotHead.getId());
        User userInfo=userService.getCurrentUser();
        StartProcessInstanceResponse response = dingService.startPurchaseApplyProcessInstance(null,
                project.getName(),
                "",
                depotHead.getRemark(),
                String.valueOf(depotHead.getTotalPrice().multiply(new BigDecimal(-1))),
                depotHead.getNumber(),
                userInfo.getWeixinOpenId()
        );
        if( response != null && response.statusCode == 200 ) {
            String dingInstanceId = response.getBody().getInstanceId();
            DepotHeadDing depotHeadDing = new DepotHeadDing();
            depotHeadDing.setCreator(userInfo.getId());
            depotHeadDing.setDepotHeadId(depotHead.getId());
            depotHeadDing.setDingInstanceid(dingInstanceId);
            depotHeadDingMapper.insert(depotHeadDing);
            return returnJson(Maps.newHashMap(), "流程发起成功", ErpInfo.OK.code);
        } else {
            return returnJson(Maps.newHashMap(), "流程发起失败", ErpInfo.ERROR.code);
        }
    }

    @PostMapping(value = "/start-process-instance/purchase-order")
    @ApiOperation(value = "发起采购申请流程")
    public String startProcessInstancePurchaseOrder(@RequestBody JSONObject jsonObject,
                                            HttpServletRequest request)throws Exception {
        Long userId = userService.getUserId(request);
        String depotHeadId = jsonObject.getString("depotHeadId");
        DepotHead depotHead = depotHeadService.getDepotHead(Long.parseLong(depotHeadId));
        if ( !depotHead.getStatus().equals(BusinessConstants.BILLS_STATUS_UN_AUDIT) ){
            return returnJson(Maps.newHashMap(), "只有未审核的单据才能发起审批流程，请刷新页面确认该单据是否已经审核完成！", ErpInfo.ERROR.code);
        }

        ContractDepotExample contractDepotExample = new ContractDepotExample();
        contractDepotExample.createCriteria().andDepotHeadIdEqualTo(depotHead.getId());
        List<ContractDepot> contractDepotList = contractDepotMapper.selectByExample(contractDepotExample);
        if ( contractDepotList.size() > 0 ){
            depotHead.setContractId(contractDepotList.get(0).getContractId());
        }
        Project project = null ;
//        if (!StringUtils.isEmpty(depotHead.getLinkNumber()) && depotHead.getLinkNumber().startsWith("CGSQ")){
//            DepotHead cgsq = depotHeadService.getDepotHead(depotHead.getLinkNumber());
//            project = getDeportProject(cgsq.getId());
//        }

        if ( depotHead.getContractId() != null ){
            Contract contract = contractMapper.selectByPrimaryKey(depotHead.getContractId());
            if ( contract != null && org.apache.commons.lang3.StringUtils.isNotBlank(contract.getProjectId())) {
                project = projectMapper.selectByPrimaryKey(Long.parseLong(contract.getProjectId()));
            }
        }

        List<DepotItemVo4WithInfoEx> dataList = depotItemService.getDetailList(Long.parseLong(depotHeadId));

        Contract contract = getDeportContract(depotHead.getId());
        Supplier supplier = supplierService.getSupplier(depotHead.getOrganId());
        User userInfo=userService.getCurrentUser();
        StartProcessInstanceResponse response = dingService.startPurchaseOrderProcessInstance(dataList,
                depotHead,
                project,
                contract,
                supplier,
                userInfo.getWeixinOpenId()
        );
        if( response != null && response.statusCode == 200 ) {
            String dingInstanceId = response.getBody().getInstanceId();
            DepotHeadDing depotHeadDing = new DepotHeadDing();
            depotHeadDing.setCreator(userInfo.getId());
            depotHeadDing.setDepotHeadId(depotHead.getId());
            depotHeadDing.setDingInstanceid(dingInstanceId);
            depotHeadDing.setDingResponse(JSON.toJSONString(response));
            depotHeadDing.setSort(Tools.getNow3());
            depotHeadDing.setInvokeStatus(BusinessConstants.BILLS_STATUS_DING_AUDIT);
            depotHeadDingMapper.insert(depotHeadDing);

            depotHead.setStatus(BusinessConstants.BILLS_STATUS_DING_AUDIT);
            depotHeadMapper.updateByPrimaryKey(depotHead);

            return returnJson(Maps.newHashMap(), "流程发起成功", ErpInfo.OK.code);
        } else {
            return returnJson(Maps.newHashMap(), "流程发起失败", ErpInfo.ERROR.code);
        }
    }

    @PostMapping(value = "/start-process-instance/lingliao-order")
    @ApiOperation(value = "发起领料申请流程")
    public String startProcessInstanceLingLiaoOrder(@RequestBody JSONObject jsonObject,
                                            HttpServletRequest request)throws Exception {
        Long userId = userService.getUserId(request);
        String depotHeadId = jsonObject.getString("depotHeadId");
        DepotHead depotHead = depotHeadService.getDepotHead(Long.parseLong(depotHeadId));
        if ( !depotHead.getStatus().equals(BusinessConstants.BILLS_STATUS_UN_AUDIT) ){
            return returnJson(Maps.newHashMap(), "只有未审核的单据才能发起审批流程，请刷新页面确认该单据是否已经审核完成！", ErpInfo.ERROR.code);
        }

        Project project = getDeportProject(depotHead.getId());

        List<DepotItemVo4WithInfoEx> dataList = depotItemService.getDetailList(Long.parseLong(depotHeadId));

        User userInfo=userService.getCurrentUser();
        StartProcessInstanceResponse response = dingService.startLingLiaoOrderProcessInstance(dataList,
                depotHead,
                project,
                userInfo.getWeixinOpenId()
        );
        if( response != null && response.statusCode == 200 ) {
            String dingInstanceId = response.getBody().getInstanceId();
            DepotHeadDing depotHeadDing = new DepotHeadDing();
            depotHeadDing.setCreator(userInfo.getId());
            depotHeadDing.setDepotHeadId(depotHead.getId());
            depotHeadDing.setDingInstanceid(dingInstanceId);
            depotHeadDing.setDingResponse(JSON.toJSONString(response));
            depotHeadDing.setSort(Tools.getNow3());
            depotHeadDing.setInvokeStatus(BusinessConstants.BILLS_STATUS_DING_AUDIT);
            depotHeadDingMapper.insert(depotHeadDing);

            depotHead.setStatus(BusinessConstants.BILLS_STATUS_DING_AUDIT);
            depotHeadMapper.updateByPrimaryKey(depotHead);

            return returnJson(Maps.newHashMap(), "流程发起成功", ErpInfo.OK.code);
        } else {
            return returnJson(Maps.newHashMap(), "流程发起失败", ErpInfo.ERROR.code);
        }
    }

    @GetMapping(value = "/sync-org")
    @ApiOperation(value = "同步人员信息")
    public String syncOrg(HttpServletRequest request)throws Exception {
        dingService.getDepartmentList();
        return returnJson(Maps.newHashMap(), "流程发起成功", ErpInfo.OK.code);
    }

    private Project getDeportProject(Long depotHeadId) throws Exception{
        ProjectDepotHeadExample example = new ProjectDepotHeadExample();
        example.createCriteria().andDepotHeadIdEqualTo(depotHeadId).andDeleteFlagEqualTo(BusinessConstants.DELETE_FLAG_EXISTS);
        List<ProjectDepotHead> projectDepotHeadList = projectDepotHeadMapper.selectByExample(example);
        if ( projectDepotHeadList.size() > 0 ){
            Long projectId = projectDepotHeadList.get(0).getProjectId();
            return projectService.getProject(projectId);
        }
        return null ;
    }

    private Contract getDeportContract(Long depotHeadId) throws Exception{
        ContractDepotExample contractDepotExample = new ContractDepotExample();
        contractDepotExample.createCriteria().andDepotHeadIdEqualTo(depotHeadId).andDeleteFlagEqualTo(BusinessConstants.DELETE_FLAG_EXISTS);
        List<ContractDepot> contractDepotList = contractDepotMapper.selectByExample(contractDepotExample);
        if ( contractDepotList.size() > 0 ){
            Long contractId = contractDepotList.get(0).getContractId();
            return contractMapper.selectByPrimaryKey(contractId);
        }
        return null ;

    }
}
